#include <iostream>
#include <unistd.h>
#include <string>


class Tickets{
  private:
    int tickets;
    pthread_mutex_t mtx;
  public:
    Tickets():tickets(1000){
      pthread_mutex_init(&mtx, nullptr);
    }
    bool GetTickets(){
      pthread_mutex_lock(&mtx);
      if (tickets <= 0){
        std::cout << "票抢完了" << std::endl;
        pthread_mutex_unlock(&mtx);
        return false;
      }
      usleep(100);
      std::cout << "我是[" << pthread_self() << "]我抢到的票是:" << tickets << std::endl;
      tickets--;
      pthread_mutex_unlock(&mtx);
      return true;
    }
    ~Tickets(){
      pthread_mutex_destroy(&mtx);
    }
};

int tickets = 1000;


void* thread_run(void* args)
{
  Tickets* ticket = (Tickets*)args;
  while (true){
    if (!ticket->GetTickets()){
      break;
    }
  }
  return nullptr;
}


int main()
{
  Tickets *ticket = new Tickets();
  pthread_t tid_arr[5] = {0};
  for (int i = 0; i < 5; i++){
    pthread_create(tid_arr + i, NULL, thread_run, (void*)ticket);
  }
  for (int i = 0; i < 5; i++){
    pthread_join(tid_arr[i], nullptr);
  }
  return 0;
}
